﻿//#define dragImageTest
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Media.Imaging;

namespace MikesDragDropBits
{
  internal class DragDropUIInjector 
  {
    public DragDropUIInjector(FrameworkElement draggedUI, Point position)
    {
      CreateDragImage(draggedUI, position);
    }
    void CreateDragImage(FrameworkElement draggedUI, Point position)
    {
#if dragImageTest
      dragImage = new Rectangle()
      {
        Width = draggedUI.ActualWidth,
        Height = draggedUI.ActualHeight,
        Fill = new SolidColorBrush(Color.FromArgb(255, 255, 0, 0))
      };
#else
      WriteableBitmap picture = new WriteableBitmap(
        (int)draggedUI.ActualWidth, (int)draggedUI.ActualHeight/*, PixelFormats.Pbgra32*/);

      picture.Render(draggedUI, new TranslateTransform());

      dragImage = new Image();
      dragImage.Source = picture;
      dragImage.Width = draggedUI.ActualWidth;
      dragImage.Height = draggedUI.ActualHeight;      
      dragImage.Stretch = Stretch.Fill;
      dragImage.IsHitTestVisible = false;
#endif // dragImageTest

      Canvas.SetLeft(dragImage, position.X);
      Canvas.SetTop(dragImage, position.Y);
    }
    public void InjectUI()
    {
      originalContent =
        UserControlContentAccessor.GetContent((UserControl)Application.Current.RootVisual);

      injectedGrid = new Grid();
      injectedGrid.IsHitTestVisible = false;

      UserControlContentAccessor.SetContent((UserControl)Application.Current.RootVisual, injectedGrid);

      injectedGrid.Children.Add(originalContent);

      dragCanvas = new Canvas()
      {
        Background = new SolidColorBrush(Color.FromArgb(0x10, 0, 0, 0))
      };
      dragCanvas.IsHitTestVisible = false;
      dragCanvas.Children.Add(dragImage);

      injectedGrid.Children.Add(dragCanvas);
    }
    public void RemoveUI()
    {
      injectedGrid.Children.Clear();

      UserControlContentAccessor.SetContent(
        (UserControl)Application.Current.RootVisual, originalContent);
    } 
    internal void ApplyDelta(double X, double Y)
    {
      Canvas.SetLeft(dragImage, Canvas.GetLeft(dragImage) + X);
      Canvas.SetTop(dragImage, Canvas.GetTop(dragImage) + Y);
    }
    Grid injectedGrid;    
    Canvas dragCanvas;
    UIElement originalContent;

#if dragImageTest
    Rectangle dragImage;
#else
    Image dragImage;
#endif // dragImageTest
  }
}